package com.naiterui.ehp.bs.b2c.order.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.bo.b2c.order.OrderBO;
import com.naiterui.ehp.bp.utils.beans.BeanUtil;
import com.naiterui.ehp.bs.b2c.order.entity.Order;
import com.naiterui.ehp.bs.b2c.order.entity.OrderItem;
import com.naiterui.ehp.bs.b2c.order.repository.IOrderItemRepository;
import com.naiterui.ehp.bs.b2c.order.repository.IOrderRepository;
import com.naiterui.ehp.bs.b2c.order.service.IOrderSuperviseService;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author luao
 * @date 2021/6/17 1:50 下午
 **/
@Service
@RequiredArgsConstructor
public class OrderSuperviseServiceImpl implements IOrderSuperviseService {

    private final IOrderItemRepository orderItemRepository;
    private final IOrderRepository orderRepository;

    @Override
    public List<OrderBO> orderList(Set<Long> recomIds) {
        if (CollectionUtil.isEmpty(recomIds)) {
            return new ArrayList<>();
        }
        // 根据处方查询所有订单
        List<OrderItem> orderItemList = orderItemRepository.findAllByRecomIdIn(recomIds);
        Set<Long> orderIds = orderItemList.stream().map(OrderItem::getOrderId).collect(Collectors.toSet());
        Map<Long, Long> orderRecomMap =
            orderItemList.stream().collect(Collectors.toMap(OrderItem::getOrderId, OrderItem::getRecomId, (a, b) -> b));
        // 根据订单id集合查询
        List<Order> orderList = orderRepository.findByIdIn(orderIds);
        List<OrderBO> result = BeanUtil.copyList(orderList, new ArrayList<>(), OrderBO.class);
        result.stream().forEach(o -> o.setRecomId(orderRecomMap.get(o.getId())));
        return result;
    }
}
